package com.mazaiting.mail.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mazaiting.common.core.ex.exceptions.BaseException;
import com.mazaiting.email.constant.MailConstant;
import com.mazaiting.mail.converter.IMsgEmailSendConverter;
import com.mazaiting.mail.domain.entity.MsgEmailSend;
import com.mazaiting.mail.dto.MailAlarmDTO;
import com.mazaiting.mail.mapper.IMsgEmailSendMapper;
import com.mazaiting.mail.service.IMsgEmailSendService;
import com.mazaiting.rabbitmq.constant.MqConstant;
import com.mazaiting.rabbitmq.domain.info.MessageInfo;
import com.mazaiting.rabbitmq.service.IMqService;
import lombok.RequiredArgsConstructor;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Service;

/**
 * 邮件消息发送表 服务实现类
 *
 * @author 党海亮
 * @since 2022-04-16
 */
@Service
@RequiredArgsConstructor
public class MsgEmailSendServiceImpl extends ServiceImpl<IMsgEmailSendMapper, MsgEmailSend> implements IMsgEmailSendService {

    private final JavaMailSenderImpl mailSender;

    private final IMqService mqService;

    private final IMsgEmailSendConverter msgEmailSendConverter;

    @Override
    public boolean alarm(MailAlarmDTO mailAlarmDTO) throws BaseException {
        // 保存发送记录
        MsgEmailSend msgEmailSend = msgEmailSendConverter.dto2Entity(mailAlarmDTO);
        msgEmailSend.setFromMail(mailSender.getUsername());
        save(msgEmailSend);
        // 发送消息
        MessageInfo<String> messageInfo = new MessageInfo<>(MailConstant.EXCHANGE_EMAIL_ALARM, MailConstant.KEY_EMAIL_ALARM);
        messageInfo.setExpiration(MqConstant.DELAY_EXPIRATION_S_1);
        // 发送记录 ID
        messageInfo.setData(String.valueOf(msgEmailSend.getId()));
        mqService.sendMessage(messageInfo);

        return true;
    }
}
